package com.example.day27_videocall;

import android.content.Context;
import android.hardware.Camera;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import androidx.annotation.NonNull;

/**
 * Description:本地窗口
 * Created by Gdu on 2021/1/5 11:27.
 */

@SuppressWarnings("deprecation")
public class LocalSurfaceView extends SurfaceView implements SurfaceHolder.Callback, Camera.PreviewCallback {
    private static final String TAG = "LocalSurfaceView";
    private Camera mCamera;
    private Camera.Size size;
    private byte[] buffer;
    private EncodecPushLiveH265 encodecPushLiveH265;

    public LocalSurfaceView(Context context, AttributeSet attrs) {
        super(context, attrs);
        getHolder().addCallback(this);
    }

    //开始通讯
    public void startCaptrue(SocketLive.SocketCallback socketCallback) {
        encodecPushLiveH265 = new EncodecPushLiveH265(socketCallback,size.width,size.height);
        encodecPushLiveH265.startLive();
    }

    private void startPreview() {
        mCamera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
        Camera.Parameters parameters = mCamera.getParameters();
        size = parameters.getPreviewSize();
        try {
            mCamera.setPreviewDisplay(getHolder());
            mCamera.setDisplayOrientation(90);
            buffer = new byte[size.width * size.height * 3 / 2];
            mCamera.addCallbackBuffer(buffer);
            mCamera.setPreviewCallbackWithBuffer(this);
            mCamera.startPreview();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void surfaceCreated(@NonNull SurfaceHolder holder) {
        startPreview();
    }

    @Override
    public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(@NonNull SurfaceHolder holder) {

    }

    @Override
    public void onPreviewFrame(byte[] data, Camera camera) {
        if (encodecPushLiveH265 != null) {
            encodecPushLiveH265.encodeFrame(data);
        }
        mCamera.addCallbackBuffer(data);
    }

}
